package servlets;

import bean.User;
import db.UserMockTable;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String name=request.getParameter("yhm");
        String password=request.getParameter("pwd");
        //上面两行是获取请求包中参数，就是用户提交的账号和密码
        //下面这一行就是到数据库中读取该用户记录
        System.out.println(name);
        User user= UserMockTable.getUserByName(name);
        String msg;
        response.setContentType("text/html;charset=utf-8");
        HttpSession session=request.getSession();
        //浏览器在请求服务器时，执行到这里，上面这一行：提取请求数据包中cookie信息，寻找这个键JSESSIONID，根据这个id到服务器中寻找这个对象
        //这个对象如果存在，把对象赋值给变量，不存在，新建一个对象
        if(user==null){
            msg="该用户不存在";
            response.getWriter().write(msg);
            response.setHeader("Refresh","3;URL=/login.html");
        }else if(user.getPassword().equals(password)){
            msg="登录成功！";
            response.getWriter().write(msg+"欢迎你，"+user.getName()+"!");
            response.getWriter().write("<a href='/logout'>退出登录<a/><br/>");
            response.getWriter().write("<a href='/cart'>进入购物车选购商品<a/><br/>");
            response.getWriter().write("<a href='/pay'>进入支付<a/>");
            session.setAttribute("name",name);
            Cookie cookie=new Cookie("JSESSIONID",session.getId());
            response.addCookie(cookie);
        }else {
            msg="密码不正确";
            response.getWriter().write(msg);
            response.setHeader("Refresh","3;URL=/login.html");
        }

    }
}
